<template>
  <div>
    <div class="main_operation">
      <!-- <div class="operation_left">
                <h3 class="title" style="min-width: 100px">历史曲线</h3>
      </div>-->
      <div class="operation_right">
        <a-select showSearch :getPopupContainer="triggerNode => triggerNode.parentNode" class="mr10" style="width: 200px" v-model="formList.equipment_id" placeholder="设备名称">
            <a-select-option v-for="item in equipmentData" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
        </a-select>
        <a-range-picker class="mr10" @ok="onOk" :showTime="{defaultValue:[moment('00:00:00','HH:mm:ss'), moment('00:00:00','HH:mm:ss')] }" format="YYYY-MM-DD HH:mm:ss" :getCalendarContainer="triggerNode => triggerNode.parentNode" :placeholder="['开始时间', '结束时间']" />
        <a-button class="mr10" type="primary" @click="equipChange">搜索</a-button>
        <a-button type="primary" @click="downloadBtn">下载数据</a-button>
      </div>
    </div>
    <div class="main">
      <a-table :pagination="false" :loading="tableLoad" :columns="Fields" :dataSource="dataLists.data"
          :rowKey="record => record.datetime"
          :scroll="{x: dataLists.itemNumber || 1000, y: 500 }"
        >
        <template v-for="(col,i) in dataLists.fieldsName" :slot="col" slot-scope="text, record, index">
          <span v-if="i%2 == 0" style="color: #0961bc;" key="1">{{text}}</span>
          <span v-else style="color: #bc2f09;" key="2">{{text}}</span>
        </template>
      </a-table>
      <div class="pageBox">
        <!-- {{dataLists}} -->
        <a-pagination  :total="dataLists.total" :showTotal="total => `共 ${total} 条数据`" :pageSize="dataLists.per_page || 1"
        :defaultCurrent="1" @change="pageChange" />
      </div>
    </div>
  </div>
</template>

<script>
  import vue from 'vue';
  import { mapState, mapActions } from 'vuex';
  import { showErrors, showError, showSuccess } from '@/utils/showMsg';
  import moment from 'moment';
export default {
  name: "HistoryReport",
  data() {
    return {
      /* 通用模块 */
          //列表
        tableLoad: false,//列表loading状态
        formList:{          //列表信息
          equipment_id: undefined,
        	page: 1
        },
        selectedRowKeys: [],//勾选的id
        /* 通用模块end */
    };
  },
  mounted() {
      this.equipmentAll()
      this.getLists(false)
      if (this.$route.query.equipmentId) {
        this.formList.equipment_id = Number(this.$route.query.equipmentId)
        this.changeData()
      }
  },
  watch: {
    equipmentData() {
      if (!this.$route.query.equipmentId) {
        this.formList.equipment_id = this.equipmentData[0].id;
        this.equipChange();
      }
    },
  },
  computed: {
      ...mapState({
    		Fields: state => state.dataCenterHistory.historyFields,
    		dataLists: state => state.dataCenterHistory.historyDataLists,
        // requestCode: state => state.dataCenterHistory.requestCode,
        equipmentData: state => state.equipment.equipmentData,
    	}),
  },
  methods: {
      moment,
      /* 搜索模块 */
      onOk(value) {
        let timeA = moment(value[0]._d).format('YYYY-MM-DD HH:mm:ss')
        let timeB = moment(value[1]._d).format('YYYY-MM-DD HH:mm:ss')
        this.formList.start_time = timeA
        this.formList.end_time = timeB
      },
      equipChange(val) {
        this.changeData()
      },
      /* 搜索模块end */
      /* 通用模块 */
      ...mapActions({
        getLists: 'dataCenterHistory/dataHistoryList', //列表
        dataHistoryEexport: 'dataCenterHistory/dataHistoryEexport', //列表
        equipmentAll: 'equipment/equipmentAll', //所有设备名称
      }),
        // 重新获取列表数据
      changeData(){
        this.tableLoad = true
        setTimeout(()=> {
          this.getLists(this.formList)
          this.tableLoad = false
        }, 800);
      },
        // 页码
      pageChange(page) {
      	this.formList.page = page;
      	this.changeData()
      },
      /* 通用模块end */

      /* 导出 */
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]));
      },
      export2Excel(tHeaders, filterVals, lists, fileName) {
        let that = this;
        require.ensure([], () => {
          //这里的require的路径要写对，不然运行会有错误
          const { export_json_to_excel } = require('@/vendor/Export2Excel');
          const tHeader = tHeaders;
          const filterVal = filterVals;
          const list = lists;
          const data = that.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, `${fileName}_历史报表`);
        });
        this.dataVisible = false;
      },
      // 按钮点击触发
      downloadBtn(){
        const that = this
        if (this.formList.equipment_id == undefined) {
          this.$error({
            title: '请先选择设备进行数据筛选！',
          });
          return false
        }
        this.$confirm({
        	title: `确定下载当前所有数据嘛?`,
        	// content: `确定导出当前所有数据嘛`,
        	okText: '确定',
        	cancelText: '取消',
        	onOk() {
            showSuccess('数据较多，请耐心等待！')
            // console.log(that.formList);
            let field = ["更新日期"] //标题
				    let filter = ["datetime"] //内容过滤
            that.dataHistoryEexport(that.formList).then(res=>{
              console.log(res);
              let resData = res.data.result
              resData.fields.forEach(function(item,i){
                field.push(item.title)
                filter.push(item.key)
              })
              // 预留功能（定义导出名字）
              let equiName = ''
              that.equipmentData.forEach(item=>{
                if (item.id == that.formList.equipment_id) {
                  equiName = item.name
                }
              })
              that.export2Excel(field, filter, resData.list.data ,equiName)
            })
        	},
        });
      }
      /* 导出end */
  }
};
</script>

<style scoped>
</style>
